package com.yangwp.doutu.service.impl;

import com.google.common.collect.Maps;
import com.yangwp.doutu.dao.ImageDao;
import com.yangwp.doutu.model.Image;
import com.yangwp.doutu.service.ImageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageDao imageDao;

    @Override
    public boolean insert(Image image){
        return imageDao.insert(image) > 0;
    }

    @Override
    public Image getImageRandom(){
        try {
            Map<String, Object> cond = Maps.newHashMap();
            long count = imageDao.countImage(cond);
            int ranking = (int) (System.nanoTime() % count);
            return imageDao.getImageByRanking(ranking);
        }catch (Exception e){
            System.out.println(e);
            return null;
        }
    }

    @Override
    public Image getImageById(Integer id){
        return imageDao.getImageById(id);
    }

    @Override
    public Boolean isImageExists(String md5){
        if(StringUtils.isBlank(md5)){
            return Boolean.FALSE;
        }
        try {
            return imageDao.getImageByMd5(md5) != null;
        }catch (Exception e){
            return Boolean.FALSE;
        }

    }

}
